package com.xinqi.modules.chat.chat.official.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.core.constant.ChatRemindConstants;
import com.xinqi.common.core.constant.MQConstants;
import com.xinqi.common.core.enums.ChatRemindTypeEnum;
import com.xinqi.common.core.enums.RocketMqEnum;
import com.xinqi.common.core.enums.RocketMqRongyunEnum;
import com.xinqi.common.core.utils.PlaceholderUtils;
import com.xinqi.common.rocketmq.dto.ChatMessageMessageBody;
import com.xinqi.common.rocketmq.dto.MqMessageDTO;
import com.xinqi.common.rocketmq.event.ProducerEvent;
import com.xinqi.modules.chat.chat.official.domain.ChatRemindConfigEntity;
import com.xinqi.modules.chat.chat.official.dto.req.ChatRemindContentBatchCreateDTO;
import com.xinqi.modules.chat.chat.official.dto.req.ChatRemindContentCreateDTO;
import com.xinqi.modules.chat.chat.official.json.ChatRemindMessage;
import com.xinqi.modules.chat.chat.official.manager.ChatRemindConfigManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version V1.0
 * @Title: 融云新奇提醒MQ
 * @ClassName: com.xinqi.modules.chat.chat.official.service.impl.ChatRemindMQService.java
 * @Description:
 * @Copyright 星齐科技（云南）有限公司 - Powered By 技术部
 * @author: yyzhen
 * @date: 2023/7/27 10:11
 */
@Log4j2
@Validated
@Service("chatRemindMQService")
@RequiredArgsConstructor
public class ChatRemindMQService {

    private final ChatRemindConfigManager chatRemindConfigManager;

    /**
     * 新增 -- 新奇提醒消息记录
     *
     * @Title:
     * @MethodName: sendRemind
     * [dto]
     * @Return java.lang.Boolean
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/5/6 15:54
     */
    @Async("threadPoolTaskExecutor")
    public Boolean sendRemind(ChatRemindContentCreateDTO dto) {
        ChatRemindConfigEntity configEntity = chatRemindConfigManager.selectByUserId(dto.getUserId());
        //通知设置 -- 不接受此类提醒
        if (!checkConfig(configEntity, dto.getType().getCode())) {
            return Boolean.TRUE;
        }

        ChatRemindMessage message = convertToMessage(dto);
        //消息免打扰
        if (Objects.nonNull(configEntity) && Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getIsDisturb())) {
            message.setPushContent(null);
        }
        //新奇提醒机器人
        this.sentRemindMsg(message);

        return Boolean.TRUE;
    }

    /**
     * 批量新增 -- 新奇提醒消息记录
     *
     * @Title:
     * @MethodName: batchSendRemind
     * [list]
     * @Return java.lang.Boolean
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/5/6 15:54
     */
    @Async("threadPoolTaskExecutor")
    public Boolean batchSendRemind(ChatRemindContentBatchCreateDTO dto) {
        if (CollectionUtil.isEmpty(dto.getList())) {
            return Boolean.TRUE;
        }

        List<Long> userIds = dto.getList().stream().map(ChatRemindContentCreateDTO::getUserId).collect(Collectors.toList());

        List<ChatRemindConfigEntity> entityList = chatRemindConfigManager.selectByUserId(userIds);
        Map<Long, ChatRemindConfigEntity> map = new HashMap<>();
        entityList.forEach(entity -> map.put(entity.getUserId(), entity));

        dto.getList().forEach(item -> {
            ChatRemindConfigEntity configEntity = map.get(item.getUserId());
            //通知设置 -- 不接受此类提醒
            if (!checkConfig(configEntity, item.getType().getCode())) {
                return;
            }

            ChatRemindMessage message = convertToMessage(item);
            //消息免打扰
            if (Objects.nonNull(configEntity) && Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getIsDisturb())) {
                message.setPushContent(null);
            }
            //新奇提醒机器人
            this.sentRemindMsg(message);
        });

        return Boolean.TRUE;
    }


    /**
     * 新奇提醒通知设置，是否接收此类提醒
     *
     * @param configEntity
     * @param type
     * @return
     */
    private boolean checkConfig(ChatRemindConfigEntity configEntity, String type) {
        if (Objects.isNull(configEntity)) {
            return Boolean.TRUE;
        }
        if (Objects.equals(ChatRemindTypeEnum.COMMENT.getCode(), type)) {
            return Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getComment());
        } else if (Objects.equals(ChatRemindTypeEnum.REPLY.getCode(), type)) {
            return Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getReply());
        } else if (Objects.equals(ChatRemindTypeEnum.GIVE.getCode(), type)) {
            return Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getGive());
        } else if (Objects.equals(ChatRemindTypeEnum.JOIN_CLASS.getCode(), type)) {
            return Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getJoinClass());
        } else if (Objects.equals(ChatRemindTypeEnum.DROP_CLASS.getCode(), type)) {
            return Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getDropClass());
        } else if (Objects.equals(ChatRemindTypeEnum.IDENTITY_CHANGE.getCode(), type)) {
            return Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getIdentityChange());
        } else if (Objects.equals(ChatRemindTypeEnum.GROUP_CHANGE.getCode(), type)) {
            return Objects.equals(YesNoNumberEnum.YES.getCode(), configEntity.getGroupChange());
        }
        return Boolean.TRUE;
    }

    private ChatRemindMessage convertToMessage(ChatRemindContentCreateDTO entity) {
        ChatRemindMessage message = new ChatRemindMessage();
        message.setUserId(Objects.isNull(entity.getUserId()) ? null : entity.getUserId().toString());
        message.setRemindType(entity.getType().getCode());
        message.setContentType(entity.getContentType());
        message.setContentId(Objects.isNull(entity.getContentId()) ? null : entity.getContentId().toString());
        message.setCourseId(Objects.isNull(entity.getCourseId()) ? null : entity.getCourseId().toString());
        message.setClassId(Objects.isNull(entity.getClassId()) ? null : entity.getClassId().toString());
        message.setContent(entity.getContent());
        message.setPushContent(PlaceholderUtils.delHTMLTag(entity.getContent()));
        message.setTimes(entity.getTimes());
        message.setData(entity.getData());
        return message;
    }

    /**
     * 新奇提醒机器人
     *
     * @param remindMessage
     */
    private void sentRemindMsg(ChatRemindMessage remindMessage) {
        ChatMessageMessageBody body = new ChatMessageMessageBody();
        body.setType(RocketMqRongyunEnum.RONGYUN_REMIND_MESSAGE.getCode());
        body.setSenderId(ChatRemindConstants.REMIND);
        body.setTargetIds(new String[]{remindMessage.getUserId()});
        body.setJson(JSONObject.toJSONString(remindMessage));
        MqMessageDTO message = new MqMessageDTO(RocketMqEnum.RONGYUN_MESSAGE.getCode(), JSONObject.toJSONString(body));
        message.setMessageKey(MQConstants.REMIND_MESSAGE_KEY + remindMessage.getUserId());
        ProducerEvent.producerFifoMessage(message);
    }

}
